//
//  GradientView.swift
//  TSMediaPlayer
//
//  Created by TSYH on 2024/4/28.
//

import UIKit
import ExtensionsKit

public class GradientView: UIView {
    var colors: [UIColor]?
    var from: CGPoint = CGPoint(x: 0, y: 0)
    var to: CGPoint = CGPoint(x: 1, y: 0)
    var index: Int?
    
    public required init(colors: [UIColor]? = nil,
                  from: CGPoint = CGPoint(x: 0, y: 0),
                  to: CGPoint = CGPoint(x: 1, y: 0),
                  index: Int? = nil) {
        self.colors = colors
        self.from = from
        self.to = to
        self.index = index
        super.init(frame: .zero)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        if let colors = colors {
            setGradient(colors: colors, from: from, to: to, index: index)
        }
    }
    
    public func set(colors: [UIColor]? = nil,
                    from: CGPoint = CGPoint(x: 0, y: 0),
                    to: CGPoint = CGPoint(x: 1, y: 0),
                    index: Int? = nil) {
        self.colors = colors
        self.from = from
        self.to = to
        self.index = index
    }
}

public class GradientButton: UIButton {
    var colors: [UIColor]?
    var from: CGPoint = CGPoint(x: 0, y: 0)
    var to: CGPoint = CGPoint(x: 1, y: 0)
    var index: Int?
    
    public required init(colors: [UIColor]? = nil,
                  from: CGPoint = CGPoint(x: 0, y: 0),
                  to: CGPoint = CGPoint(x: 1, y: 0),
                  index: Int? = nil) {
        self.colors = colors
        self.from = from
        self.to = to
        self.index = index
        super.init(frame: .zero)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        if let colors = colors {
            setGradient(colors: colors, from: from, to: to, index: index)
        }
    }
    
    public func set(colors: [UIColor]? = nil,
                    from: CGPoint = CGPoint(x: 0, y: 0),
                    to: CGPoint = CGPoint(x: 1, y: 0),
                    index: Int? = nil) {
        self.colors = colors
        self.from = from
        self.to = to
        self.index = index
    }
}
